package com.evamay.mytinkerdemo

import android.Manifest
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.os.Process
import android.os.Process.killProcess
import com.evamay.mytinkerdemo.utils.FileUtils
import com.evamay.mytinkerdemo.utils.HashCodeUtils
import com.evamay.mytinkerdemo.utils.PermissionUtils
import com.evamay.mytinkerdemo.utils.Utils
import com.orhanobut.logger.Logger
import com.tencent.tinker.lib.tinker.TinkerInstaller
import com.tencent.tinker.loader.shareutil.ShareTinkerInternals
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File

class MainActivity : AppCompatActivity() {
    private val PERMISSIONS= arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE
            ,Manifest.permission.WRITE_EXTERNAL_STORAGE)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Logger.e("load complete")
        Logger.e("Apk code: ${HashCodeUtils.getHash(this)}")
        /**
         * 创建文件夹用来保存下载的更新包
         */

        PermissionUtils.requestMorePermissions(this,PERMISSIONS,100)
        btn_load_tinker.setOnClickListener{
            loadPatch()
        }
        btn_kill_tinker.setOnClickListener{
            killAppProcess()
        }
        try {
            var file=File(FileUtils.baseFilePath)
            if (!file.exists()) {
                file.mkdirs()
            }
        } catch (e: Exception) {
            Logger.e(e.message)
        }

    }

    override fun onResume() {
        super.onResume()
        Utils.isBackground=true
    }

    override fun onPostResume() {
        super.onPostResume()
        Utils.isBackground=true
    }
    /**
     * 结束进程
     */
    private fun killAppProcess() {
        ShareTinkerInternals.killAllOtherProcess(applicationContext)
        killProcess(Process.myPid())
    }

    /**
     * 加载热更新插件
     */
    private fun loadPatch() {
        Logger.e("load path : ${FileUtils.baseFilePath}patch_signed_7zip.apk")
        TinkerInstaller.onReceiveUpgradePatch(applicationContext, FileUtils.baseFilePath+"patch_signed_7zip.apk")
    }
}
